package com.dylan.structure.linked.single;

import lombok.Data;

/**
 * 单向链表
 *
 * @author zhangshaojian
 * @date 2022/7/12 14:49
 */
@Data
public class SingleLinkedList<T> {
    private int size;
    private Node<T> head;
    private Node<T> tail;

    public SingleLinkedList() {
        this(null);
    }

    public SingleLinkedList(T source) {
        if (source != null) {
            Node<T> head = new Node<>(source);
            size = 1;
            this.head = head;
        } else {
            size = 0;
            head = null;
        }
        tail = head;
    }

    public Boolean add(T source) {
        if (source == null) {
            System.out.println("数据为空");
            return Boolean.FALSE;
        }
        Node<T> data = Node.of(source);
        if (head == null) {
            head = data;
        } else {
            tail.next = data;
        }
        tail = data;
        return Boolean.TRUE;
    }

    public void list() {
        Node<T> temp = head;
        System.out.println(temp.data);
        while (temp.next != null) {
            temp = temp.next;
            System.out.println(temp.data);
        }
    }

    @Data
    private static class Node<T> {
        T data;
        Node<T> next;

        public Node(T current) {
            data = current;
            next = null;
        }

        static <T> Node<T> of(T source) {
            return new Node<>(source);
        }
    }
}
